package com.sunhao.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sunhao.gulimall.product.service.CategoryBrandRelationService;
import com.sunhao.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunhao.common.utils.PageUtils;
import com.sunhao.common.utils.Query;

import com.sunhao.gulimall.product.dao.CategoryDao;
import com.sunhao.gulimall.product.entity.CategoryEntity;
import com.sunhao.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    public RedissonClient redisson;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有数据
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子结构
        //2.1 查找所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity ->
                categoryEntity.getParentCid() == 0
        )).map(
                menu->{
                    //递归查询子分类
                    menu.setChildren(getChildrens(menu,entities));
                    return menu;
                }
        ).sorted(
                (menu1,menu2)->{
                    return (menu1.getSort()==null?0 :menu1.getSort()) - (menu2.getSort()==null?0 :menu2.getSort());
                }
        ).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，在其他地方是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 返回CategoryPath
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return  parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新
     * @param category
     */
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatalogJson'")
    })
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 查询所有一级分类
     * @return
     */
    @Cacheable(value = {"category"},key = "'getLevel1Categorys'")
    @Override
    public List<CategoryEntity> getLvel1Categorys() {
        List<CategoryEntity> list = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return  list;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }

    /**
     * 查询二级三级分类并封装 利用缓存机制
     * @return
     */
    @Cacheable(value = "category",key = "'getCatalogJson'")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    /**
     * 查询二级三级分类并封装 利用缓存机制
     * @return
     */
    //@Override
    public Map<String, List<Catelog2Vo>> getCatalogJson2()
    {
        //1.加入缓存逻辑，缓存中存储的数据是JSON字符串 json跨语言跨平台兼容
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if (StringUtils.isEmpty(catalogJSON))
        {
            //缓存中没有，从数据库中查询
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();

            return catalogJsonFromDB;
        }

        //利用alibaba的fastjson的parseObject来转换成我们需要的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});

        return result;
    }

    //从数据库中查询所有的三级分类数据
    public Map<String, List<Catelog2Vo>> getDataFromDB()
    {
        //用户获取到锁之后应该先在缓存中查询一次，避免上一个用户已经查到并且放到缓存中
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if (!StringUtils.isEmpty(catalogJSON))
        {
            //利用alibaba的fastjson的parseObject来转换成我们需要的对象
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});

            return result;
        }

        //1.查出所有的一级分类
        List<CategoryEntity> lvel1Categorys = this.getLvel1Categorys();
        //2.封装数据
        Map<String, List<Catelog2Vo>> collect1 = lvel1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //2.1 查询该一级分类下的二级分类
            List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            //2.2 封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //查询三级分离
                    List<CategoryEntity> level3Categorys = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (level3Categorys != null) {
                        List<Catelog2Vo.Category3Vo> collect = level3Categorys.stream().map(l3 -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        //将查询结果转化为JSON字符串存储
        String s = JSON.toJSONString(collect1);
        redisTemplate.opsForValue().set("catalogJSON",s);

        return collect1;
    }


    /**
     * 通过Redisson的分布式锁从数据库中查询所有的三级分类数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDBWithRedissonLock()
    {
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();

        }finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    //从数据库中查询所有的三级分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        //给查询数据库的操作加锁，SpringBoot的所有组件在容器中都是单例的，所以可以加锁成功
        //synchronized (this)是本地锁，无法应对分布式场景
        synchronized (this)
        {
            Map<String, List<Catelog2Vo>> dataFromDB = getDataFromDB();
            return dataFromDB;
        }
    }

    /**
     * 通过递归获取整个路径
     * @param catelogId
     * @param paths
     * @return
     */
    private List<Long> findParentPath(Long catelogId,List<Long> paths)
    {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!= 0)
        {
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 根据当前根节点查询整个category集合中的所有子目录
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all)
    {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //递归出口，当前目录的父id == root的id
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(
                categoryEntity -> {
                    //如果当前子目录还有下一级子目录，递归查询
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }
        ).sorted(
                (menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }
        ).collect(Collectors.toList());
        return children;
    }

}